<template>
  <Splitpanes class="main" style="height: 100%">
    <Pane min-size="0">
      <div id="map" class="map"></div>
    </Pane>
    <Pane min-size="0">
      <div class="grid">
        <a-table :columns="columns" :data-source="tableData" row-key="id" bordered size="small" :scroll="{ y: '100%' }"
          :row-class-name="rowClassName" :row="rowProps" />
      </div>
    </Pane>
  </Splitpanes>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as turf from '@turf/turf';
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import { Map as MtkMap, TileLayer, GroupTileLayer, GeoJSONVectorTileLayer,Extent } from 'maptalks-gl'

let map = null
let viewLayer = null
let features = []
let featureMap = new Map()

const selectedFeatureId = ref(null)
const highLightKey = 'highlight'

const tableData = ref([])
const columns = ref([])

function cancelHighLight(layer) {
  layer.cancelHighlight([highLightKey])
}

function highlightFeature(feature, layer) {
  cancelHighLight(layer)
  layer.highlight([
    {
      id: feature.id,
      plugin: 'line',
      name: highLightKey,
      color: 'red',
    },
  ])
}

/** 统一选中处理 */
function setSelectedFeature(id) {
  if (id === selectedFeatureId.value) return // 重复点击不处理

  selectedFeatureId.value = id
  if (id == null) {
    cancelHighLight(viewLayer)
    return
  }

  const feature = viewLayer.getFeature(id)
  if (feature) {
    highlightFeature(feature, viewLayer)
    const center = feature.getCenter?.() || feature.getCoordinates?.()[0]
    if (center) map.setCenter(center)
    scrollToRow(id)
  }
}

function scrollToRow(id) {
  nextTick(() => {
    const row = document.querySelector(`.ant-table-row[data-row-key="${id}"]`)
    if (row && row.scrollIntoView) {
      row.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  })
}

onMounted(() => {
  map = new MtkMap('map', {
    center: [122, 41],
    zoom: 8,
    attribution: false,
    baseLayer: new GroupTileLayer('base', [
      new TileLayer('td-vec', {
        urlTemplate:
          'http://t{s}.tianditu.gov.cn/DataServer?T=vec_w&X={x}&Y={y}&L={z}&tk=a6401c00bccf85f0e2bfb591e6ecc4c2',
        subdomains: [0, 1, 2],
      }),
      new TileLayer('td-cva', {
        urlTemplate:
          'http://t{s}.tianditu.gov.cn/DataServer?T=cva_w&X={x}&Y={y}&L={z}&tk=a6401c00bccf85f0e2bfb591e6ecc4c2',
        subdomains: [0, 1, 2],
      }),
    ]),
  })

  const style = {
    style: [
      {
        renderPlugin: {
          type: 'fill',
          dataConfig: { type: 'fill', only2D: true },
        },
        symbol: {
          visible: true,
          polygonFill: 'rgba(0, 200, 0, 0.5)',
          polygonOpacity: 1,
        },
        filter: ['==', '$type', 'Polygon'],
      },
      {
        name: 'line',
        renderPlugin: {
          type: 'line',
          dataConfig: { type: 'line', only2D: true },
        },
        symbol: {
          visible: true,
          lineOpacity: 1,
          lineWidth: 3,
          lineColor: '#ff6600',
          lineJoin: 'round',
          lineCap: 'round',
          lineStrokeWidth: 1,
          lineStrokeColor: '#ffffff',
        },
        filter: ['==', '$type', 'LineString'],
      },
    ],
  }

  viewLayer = new GeoJSONVectorTileLayer('geojson0', { style })
  viewLayer.addTo(map)
  // 地图点击事件，调用统一选中处理
  map.on('click', (e) => {
    const data = viewLayer.identify(e.coordinate)
    if (!data || !data.length) {
      setSelectedFeature(null)
      return
    }
    const feature = data[data.length - 1].data.feature
    setSelectedFeature(feature.id)
  })
})

// 设置数据（供外部调用）
const setData = (geojson) => {
  if (!viewLayer) return
  viewLayer.setData(geojson)
  debugger
  const bbox = turf.bbox(geojson); // 返回 [minX, minY, maxX, maxY]
  const extent = new Extent(bbox[0], bbox[1], bbox[2], bbox[3]);
  map.fitExtent(extent, 0, { animation: true });
  features = geojson.features || []
  featureMap.clear()
  const props = features.map((f, i) => {
    const id = f.id ?? i
    featureMap.set(id, { id, ...f.properties })
    return { id, ...f.properties }
  })

  tableData.value = props

  if (features.length > 0) {
    const keys = Object.keys(features[0].properties || {})
    columns.value = keys.map((key) => ({
      title: key,
      dataIndex: key,
      key: key,
    }))
    columns.value.unshift({ title: 'ID', dataIndex: 'id', key: 'id' })
  } else {
    columns.value = []
  }

  nextTick(() => {
    selectedFeatureId.value = null
    cancelHighLight(viewLayer)
  })
}

// 点击表格行事件绑定需要这样写
const rowProps = (record) => ({
  onClick: () => {
    setSelectedFeature(record.id)
  },
})

// 表格行高亮样式
const rowClassName = ({ id }) => {
  return selectedFeatureId.value === id ? 'row-highlight' : ''
}

defineExpose({ setData })
</script>

<style scoped>
.main {
  width: 100%;
  height: 100%;
}

::v-deep(.splitpanes__splitter) {
  width: 8px !important;
  background-color: #d9d9d9;
  cursor: col-resize;
  transition: background-color 0.2s;
}

::v-deep(.splitpanes__splitter:hover) {
  background-color: #40a9ff;
}

.map,
.grid {
  width: 100%;
  height: 100%;
  overflow: auto;
  padding: 10px;
  box-sizing: border-box;
}

.row-highlight {
  background-color: #e6f7ff !important;
  color: #1890ff !important;
}
</style>